﻿CREATE PROCEDURE s_PurchaseContract_SendBulk
	@StatusFromID int,
	@StatusToID int,
	@Filter varchar(512)
AS

IF ISNULL(@Filter,'') = ''BEGIN
	UPDATE t_Loan SET StatusID = @StatusToID WHERE StatusID = @StatusFromID
	RETURN
END

IF NOT OBJECT_ID('GetLoansByFilter_') IS NULL DROP FUNCTION GetLoansByFilter_

DECLARE @FuncSQL varchar(max)
SELECT @FuncSQL = 
REPLACE(
REPLACE(Text,'SELECT ''''c',
'SELECT LoanID FROM v_PurchaseContract WHERE '+@Filter
),'GetLoansByFilter','GetLoansByFilter_'
)
FROM sys.objects o INNER JOIN syscomments c ON o.object_id = c.id WHERE o.Name = 'GetLoansByFilter'

EXEC(@FuncSQL)

UPDATE L SET StatusID = @StatusToID 
FROM t_Loan L
INNER JOIN GetLoansByFilter_ ()LBF ON LBF.LoanID = L.ID
WHERE L.StatusID = @StatusFromID


